package cn.xunjie.ymcc.mq.listener;

import cn.xunjie.ymcc.domain.PayOrder;
import cn.xunjie.ymcc.dto.PayNotifyDto;
import cn.xunjie.ymcc.service.IPayOrderService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@RocketMQTransactionListener(
        txProducerGroup = "service-pay-tx-group"  //要和发送事务消息指明的名字一致
)
@Slf4j
public class PayNotifyRocketMqListener implements RocketMQLocalTransactionListener {
    @Autowired
    private IPayOrderService payOrderService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        PayOrder payOrder = (PayOrder)arg;
        PayOrder order = payOrderService.selectOrderNo(payOrder.getOrderNo());
        if(order.getPayStatus() != PayOrder.STAE_WAIT_PAY){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        payOrderService.updateById(payOrder);
        return RocketMQLocalTransactionState.COMMIT;//执行本地事务成功
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            byte[] bodyTmp = (byte[])message.getPayload();
            String notifyDto = new String(bodyTmp, StandardCharsets.UTF_8);
            PayNotifyDto dto = JSONObject.parseObject(notifyDto, PayNotifyDto.class);
            if(dto != null){
                return RocketMQLocalTransactionState.UNKNOWN;
            }
            PayOrder order = payOrderService.selectOrderNo(dto.getOrderNo());
            if(order == null){
                return RocketMQLocalTransactionState.UNKNOWN;
            }
            if(order.getPayStatus() == PayOrder.STAE_PAY_SUCCESS){
                return RocketMQLocalTransactionState.COMMIT;
            }
            return RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }

}
